﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ERMSys.Framework.Utilities;
using Se7en.Admin.Model;

namespace Se7en.Admin.Business
{
    public static partial class AccountingBLL
    {
        public static List<User> User_GetPaging(this AdminContext context, int pageIndex, int pageSize, out int total)
        {
            return context.Users.OrderBy(u => u.LoginName).ToListPaging(pageIndex, pageSize, out total);
        }

        public static User User_Login(this AdminContext context, string loginName, string password, bool isAdmin)
        {
            return context.Users.FirstOrDefault(e => e.LoginName.ToLower() == loginName.ToLower() && e.Password == password && e.IsSystem == isAdmin);
        }

        public static List<User> User_GetAll(this AdminContext context, int pageIndex, int pageSize, out int total)
        {
            return context.Users.OrderBy(u => u.LoginName).ToListPaging(pageIndex, pageSize, out total);
        }

        public static bool User_IsExistedEmail(this AdminContext context, User user)
        {
            if (user.UserID > 0)
                return context.Users.FirstOrDefault(e => e.UserID != user.UserID && user.Email.ToLower() == e.Email.ToLower() && e.IsSystem == user.IsSystem) != null;
            else
                return context.Users.FirstOrDefault(e => user.Email.ToLower() == e.Email.ToLower() && e.IsSystem == user.IsSystem) != null;
        }

        public static bool User_IsExistedLoginName(this AdminContext context, User user)
        {
            if (user.UserID > 0)
                return context.Users.FirstOrDefault(e => e.UserID != user.UserID && user.LoginName.ToLower() == e.LoginName.ToLower() && e.IsSystem == user.IsSystem) != null;
            else
                return context.Users.FirstOrDefault(e => user.LoginName.ToLower() == e.LoginName.ToLower() && e.IsSystem == user.IsSystem) != null;
        }

        public static User User_GetByID(this AdminContext context, int userID)
        {
            return context.Users.FirstOrDefault(e => e.UserID == userID);
        }

        public static bool User_DeleteByID(this AdminContext context, int userID)
        {
            bool ok = true;
            try
            {
                User user = context.Users.FirstOrDefault(u => u.UserID == userID);
                if (user != null)
                    context.DeleteObject(user);
            }
            catch
            {
                ok = false;
            }
            return ok;
        }
    }
}
